import React, { Component } from 'react'
import { Form, Button, Table, Row, Col, Popconfirm, Icon, Modal, Input, Checkbox } from 'antd';
import * as fetch from '../../utils/http'

class DeviceChild extends Component {

    constructor(props) {
        super(props)
        this.state = {
            visibleChildModal: false,
            visibleSignalModal: false,
            showErrorMsg: false,
            deviceChildList: [],
            deviceSignalList: [],
            selectedRowKeys: [],
            currenChild: {}
        }
        this.getAllChild()
        this.getAlldeviceSignalList()
    }

    getAllChild() {
        fetch.get('DeviceItem/GetDeviceItems').then(res => {
            this.setState({
                deviceChildList: res.data || []
            })
        })
    }

    getAlldeviceSignalList() {
        fetch.get('DeviceItemProperty/GetDeviceItemPropertys').then(res => {
            this.setState({
                deviceSignalList: res.data || []
            })
        })
    }

    addChild = () => {
        const item = this.state.currenChild
        const AddChildModal = Form.create()(props => {
            const { form } = props
            const { getFieldDecorator } = form;

            const onSaveSignal = () => {
                form.validateFields((err, values) => {
                    if (!err) {
                        this.setState({
                            visibleChildModal: false
                        })
                        const params = values
                        if (item.itemID) {
                            fetch.post('DeviceItem/Edit', params).then(res => {
                                this.getAllChild()

                            })
                        } else {
                            fetch.post('DeviceItem/Add', params).then(res => {
                                this.getAllChild()
                            })
                        }
                        this.setState({
                            currenChild: {}
                        })
                    }
                })
            }

            const cancelModal = () => {
                form.resetFields()
                this.setState({
                    visibleChildModal: false
                })
            }

            return (
                < Modal title={this.state.modalTitle}
                    cancelText='取消'
                    onCancel={cancelModal}
                    onOk={onSaveSignal}
                    okText='确定'
                    visible={this.state.visibleChildModal}
                >
                    <Form className="login-form">
                        <Form.Item label="id" className="hidden-input">
                            {getFieldDecorator('id', {
                                initialValue: item.itemID
                            })(
                                <Input
                                    className="h-40"
                                    type="text"
                                    placeholder="子项名称"
                                />,
                            )}
                        </Form.Item>
                        <Form.Item label="子项名称" >
                            {getFieldDecorator('itemName', {
                                initialValue: item.itemName
                            })(
                                <Input
                                    className="h-40"
                                    type="text"
                                    placeholder="子项名称"
                                />,
                            )}
                        </Form.Item>
                    </Form>
                </ Modal>
            )
        })
        return <AddChildModal />
    }

    newChild() {
        this.setState({
            currenChild: {},
            visibleChildModal: true
        })
    }

    onEditChild(item) {
        this.setState({
            currenChild: item,
            visibleChildModal: true
        })
    }

    onEditSignal(item) {
        if (item.deviceItemProperties.length) {
            for (const child of item.deviceItemProperties) {
                const current = this.state.deviceSignalList.filter(item => item.id === child.deviceItemProperty.id)[0]
                current.tag = child.tag
            }
        }
        this.setState({
            selectedRowKeys: item.deviceItemProperties.map(item => item.deviceItemProperty.id),
            currenChild: item,
            visibleSignalModal: true
        })
    }

    onDelChild(item) {
        const { itemID } = item
        fetch.post('DeviceItem/Delete', { id: itemID }).then(res => {
            this.getAllChild()
        })
    }

    onSelectChange = selectedRowKeys => {
        this.setState({ selectedRowKeys }, () => {
            console.log(this.state.selectedRowKeys)
        });
    }

    resetDeviceSignal() {
        const { deviceSignalList } = this.state
        deviceSignalList.forEach(item => {
            item.tag = ''
        })
    }

    onSignalTagChange = (item, e) => {
        const { deviceSignalList } = this.state
        const current = deviceSignalList.filter(child => child.id === item.id)[0]
        current.tag = e.target.value
        this.setState({
            deviceSignalList
        })
    }

    addSignal() {
        let params = {}
        const { selectedRowKeys } = this.state
        if (!selectedRowKeys.length) {
            params = {
                deviceItemID: this.state.currenChild.itemID,
                deviceItemProperties: []
            }

        } else {
            const arr = []
            for (let item of this.state.deviceSignalList) {
                if (selectedRowKeys.includes(item.id)) {
                    const obj = {
                        deviceItemPropertyID: item.id
                    }
                    arr.push(obj)
                }
            }

            params = {
                deviceItemID: this.state.currenChild.itemID,
                deviceItemProperties: arr
            }
        }

        fetch.post('DeviceItem/RelatedDeviceDeviceItem', params).then(res => {
            this.getAllChild()
            this.setState({
                visibleSignalModal: false,
                showErrorMsg: false
            })
            this.resetDeviceSignal()
        })
    }

    render() {
        const { deviceChildList, deviceSignalList, selectedRowKeys } = this.state

        const columns = [
            {
                title: '子项名称',
                dataIndex: 'itemName',
                key: 'itemName'
            },
            {
                title: '子项信号',
                key: 'signal',
                render: item => (
                    <div onClick={this.onEditSignal.bind(this, item)} style={{ fontSize: '14px', cursor: 'pointer' }} >
                        <Icon type="plus-square" style={{ marginRight: '5px' }}></Icon>
                        {
                            item.deviceItemProperties.length ?
                                item.deviceItemProperties.map((child, index) => {
                                    return (
                                        <span key={index}>{child.deviceItemProperty.signNo}{index === item.deviceItemProperties.length - 1 ? '' : '、'}</span>
                                    )
                                })
                                :
                                ''
                        }
                    </div>
                )
            },
            {
                title: '操作',
                width: 100,
                render: item => (
                    <Row type="flex" justify="space-between">
                        <Col>
                            <Button type="primary" size="small" onClick={this.onEditChild.bind(this, item)} icon="form"></Button>
                        </Col>
                        <Col>
                            <Popconfirm
                                onConfirm={this.onDelChild.bind(this, item)}
                                title="确定删除吗？"
                                okText="删除"
                                cancelText="取消"
                                icon={<Icon type="question-circle-o" style={{ color: 'red' }} />}
                            >
                                <Button type="danger" size="small" icon="delete"></Button>
                            </Popconfirm>
                        </Col>
                    </Row>
                )
            }
        ]

        const InputItem = (item) => {
            return (
                <Input value={item.tag} onChange={(e) => this.onSignalTagChange(item, e)}></Input>
            )
        }

        const menusColumns = [
            {
                title: '设备信号',
                key: 'signNo',
                dataIndex: 'signNo',
            },
            // {
            //     title: '信号标签',
            //     render: item => (InputItem(item))
            // },
        ]

        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };

        return (
            <div>
                <h3>设备管理 - 设备子项</h3>
                <Button type="primary" onClick={this.newChild.bind(this)}>新增设备子项</Button>
                <div style={{ padding: '20px 0px' }}>
                    <Table bordered dataSource={deviceChildList} columns={columns} rowKey="itemID" pagination={false}></Table>
                </div>
                <Modal
                    cancelText='取消'
                    okText='确定'
                    title='设备信号'
                    onOk={this.addSignal.bind(this)}
                    onCancel={() => {
                        this.resetDeviceSignal()
                        this.setState({
                            visibleSignalModal: false
                        })
                    }}
                    visible={this.state.visibleSignalModal}>
                    {
                        this.state.showErrorMsg ?
                            <p style={{ color: 'red' }}>请检查已选的信号，是否正确填写标签</p> :
                            ''
                    }
                    <Table bordered rowSelection={rowSelection} dataSource={deviceSignalList} columns={menusColumns} rowKey="id" pagination={false}></Table>
                </Modal>
                {
                    this.addChild()
                }

            </div>
        );
    }
}

export default DeviceChild;